package eighth_day;

/**
 * 字符串逆置，如 "I am a student" 逆置为 "student a am I" 。
 */
public class ReverseSentence {
    public static String reverseSentence(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        StringBuilder res = new StringBuilder();
        String[] arr = str.split(" ");
        for (int i = arr.length - 1; i >= 0; --i) {
            res.append(arr[i]);
            if (i > 0) {
                res.append(" ");
            }
        }
        return res.toString();
    }

    public static void reverse(char[] arr, int start, int end) {
        // 逆转字符数组的一部分
        while (start < end) {
            char tmp = arr[start];
            arr[start] = arr[end];
            arr[end] = tmp;
            start ++;
            end --;
        }
    }

    public static String answer(String str) {
        if (str == null || str.length() <= 1) {
            return str;
        }
        char[] arr = str.toCharArray();
        reverse(arr, 0, arr.length - 1);
        int start = 0;
        int end = 0;
        while (end < arr.length) {
            if (arr[end] == ' ') {
                reverse(arr, start, end - 1);
                start = end + 1 < arr.length ? end + 1 : start;
            }
            end ++;
        }
        StringBuilder s= new StringBuilder();
        for (char c : arr) {
            s.append(c);
        }
        return s.toString();
    }

    public static void main(String[] args) {
        String str = "I am a student";
        System.out.println(answer(str));
    }
}
